<template>
  <view class="app-layout">
    <!-- <app-header /> -->
    <view class="app-main">
      <app-sider pageKey="vip" />
      <view class="app-content">
        <view class="navbar-con">
          <view class="navbar-bar">
            <view v-for="(tab, index) in tabList" :key="index" class="tab-item" :class="{ active: currentTab == index }"
              @click="handlecurrentTab(index)">
              {{ tab }}
            </view>
          </view>
        </view>
        <template v-if="currentTab == 0">
          <view class="tabs-wrapper">
            <u-tabs :list="tabListAll" @click="tabClick1" :scrollable="true" keyName="name"
              :activeStyle="{ color: '#0F90FD', fontWeight: '500', fontSize: '16px' }">
              <template #content="{ item, keyName, index }">
                <view style="position: relative">
                  {{ item[keyName] }}
                  <u-badge type="error" max="99" :value="item.num" :absolute="true"
                    :offset="getOffset(item.num)"></u-badge>
                </view>
              </template>
            </u-tabs>
          </view>
          <view class="order-search">
            <view v-for="(tab, index) in tabType" :key="index" class="type-item"
              :class="{ activeType: currentTabType == index }" @click="handlecurrentTabType(index)">
              {{ tab }}
            </view>
            <u-search placeholder="请输入会员名称" v-model="pageInfo.keyword" clearable bgColor="#fff" borderColor="#e5e5e5"
              :showAction="false" @search="handleSearch" @clear="handleReset"></u-search>

            <view class="flex-row" style="flex: 1">
              <u-button type="primary" text="搜索" @click="handleSearch"></u-button>
              <u-button :plain="true" text="重置" @click="handleReset"></u-button>
            </view>
          </view>
        </template>
        <view class="vip-table" v-if="currentTab == 0">
          <scroll-view scroll-y="true" ref="scrollView" style="height: 100%; width: 100%"
            @scrolltolower="onScrollToLower">
            <template v-if="goodsList.length>0">
              <!-- /static/imgs/avatar.png -->
              <view class="item-card" v-for="(item, index) in goodsList" :key="index" @click.prevent="handelDetail">
                <image class="item-icon" :src="item.headPortrait?item.headPortrait:'/static/imgs/avatar.png'" mode="">
                </image>
                <view class="right-area">
                 <view class="" style="display: flex;gap:23px">
                   <view class="item-name">{{item.nickName}}</view>
                   <view class="item-name">会员等级：{{item.levelName}}</view>
                 </view>
                  <view class="middle-area">
                    <!-- <view class="info-item elliple">会员等级：{{item.levelName}}</view> -->
                    <view class="info-item">手机号：{{item.phone}}</view>
                    <text class="status">
                      状态：
                      <text class="status-dot"
                        :class="{ enable: item.status == '0', disable: item.status =='1' }"></text>
                      {{ item.status === '0' ? '启用' : '禁用' }}
                    </text>
                    <view class="info-item">注册时间：{{item.registerDate}}</view>

                    <view class="right-btn">
                      <view class="operate-btn edit" @click.stop="handleEdit(item)">
                        <image src="/static/imgs/edit.png" mode=""></image>
                        编辑
                      </view>
                      <view class="operate-btn" @click.stop="handleAdjust(item)">
                        <image src="/static/imgs/adjust.png" mode=""></image> 积分调整
                      </view>

                    </view>

                  </view>
                </view>
              </view>

            </template>
            <template v-else>
              <view class="empty-box" style="text-align: center;padding-top: 12vh;">
                <image src="/static/imgs/emptyW.png" mode="widthFix" style="width: 240px;"></image>
                <view class="text1" style="color: #999;">暂无数据</view>
              </view>
            </template>
          </scroll-view>


        </view>

        <membershipLevel v-if="currentTab == 1" :key="componentKey"
          style="display: flex; flex-direction: column;flex: 1; overflow: hidden;" />
        <interests v-if="currentTab == 2" :key="componentKey"
          style="display: flex; flex-direction: column;flex: 1; overflow: hidden;" />
        <attribute v-if="currentTab == 3" :key="componentKey"
          style="display: flex; flex-dire ction: column; flex: 1;overflow: hidden;" />
        <editForm :showPopup="showEditPopup" v-if="showEditPopup" :detailInfo="detailInfo" @closePopup="closeEditPopup"
          @surePopup="sureEditPopup" />
      </view>

    </view>
  </view>
</template>
<script setup>
  import interests from './interests/index.vue'
  import membershipLevel from './membershipLevel/index.vue'
  import attribute from './attribute/index.vue'
  import editForm from './components/editForm.vue'
  import {
    ref,
    computed,
    nextTick,
    reactive,
  } from 'vue'
  import {
    onLoad,
    onShow
  } from '@dcloudio/uni-app'
  import {
    getLevelPage,
    getsassMemberPage
  } from '@/requests/apis/vip'
  let showEditPopup = ref(false)
  let currentSelectedId = ref(-1)
  let currentTab = ref(0)
  let currentTabType = ref(0)
  let tabList = ref(['会员列表', '会员等级', '会员权益', '已注销会员'])
  let tabType = ref(['全部', '正常', '锁定'])
  let componentKey = ref(0)
  let pageInfo = reactive({
    total: 0,
    page: 1,
    limit: 20,
    keyword: '',
    status: undefined,
    levelName: undefined,
  });
  let detailInfo=ref({})
  const tabListAll = ref([{
      name: '全部',
      num: 0,
    },
    {
      name: 'lv1',
      num: 0,
    },
    {
      name: 'lv2',
      num: 0,
    },
    {
      name: 'lv3',
      num: 0,
    },
  ])
  const goodsList = ref([{
    status: 0
  }, {
    status: 1
  }, {
    status: 0
  }, {
    status: 0
  }, {
    status: 0
  }, {
    status: 0
  }, {
    status: 0
  }, {
    status: 0
  }])
  let isMergeRequest = false;
  onLoad(() => {
  })
  onShow(async () => {
    // #ifdef APP-PLUS
    uni.hideTabBar()
    // #endif
    pageInfo.categoryIds = undefined
    currentSelectedId.value = -1
     getLevelList()
    getMerge()
    if (currentTab.value === 1) {
      currentTab.value = 0;
      await nextTick();
      currentTab.value = 1;
      await nextTick();
      componentKey.value++;
    } else if (currentTab.value === 2) {
      currentTab.value = 0;
      await nextTick();
      currentTab.value = 2;
      await nextTick();
      componentKey.value++;
    } else if (currentTab.value === 3) {
      currentTab.value = 0;
      await nextTick();
      currentTab.value = 3;
      await nextTick();
      componentKey.value++;
    }
  })
  const getMerge = () => {
    const prevPage = pageInfo.page;
    if (prevPage !== 1) {
      isMergeRequest = true;
      pageInfo.limit = prevPage * 20;
      pageInfo.page = 1;
      getproductPage('merge');
    } else {
      pageInfo.page = 1;
      pageInfo.limit = 20;
      getproductPage();
    }
  };

  const onScrollToLower = (e) => {
    if (pageInfo.page * pageInfo.limit < pageInfo.total && goodsList.value.length >= 20) {
      pageInfo.page++;
      getproductPage('add');
    }
  }
  const getOffset = (num) => {
    const str = (num || 0).toString();
    const len = str.length;
    // 根据字符长度返回不同的offset值
    if (len === 1) {
      return [-10, -15]; // 1位数字的偏移
    } else if (len === 2) {
      return [-10, -25]; // 2位数字的偏移
    } else {
      return [-10, -30]; // 3位及以上数字的偏移
    }
  };
  const getLevelList = async () => {
    const res = await getLevelPage({
      keyword: "",
      status:0
    });
    const totalCreator = res.Result.reduce((sum, item) => {
      const creatorNum = Number(item.creator) || 0;
      return sum + creatorNum;
    }, 0);

    const levelList = res.Result.map((item) => ({
      name: item.levelName,
      id: item.id,
      num: Number(item.creator) || 0,
    }));

    tabListAll.value = [{
        name: "全部",
        id: undefined,
        num: totalCreator,
      },
      ...levelList,
    ];
  };
  const getproductPage = async (type) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    try {
      let res = await getsassMemberPage({
        ...pageInfo,
      })
      pageInfo.total = res.Result.total
      if (type === 'merge') {
        goodsList.value = res.Result.records || [];
        pageInfo.page = Math.ceil(goodsList.value.length / 20);
        pageInfo.limit = 20;
        isMergeRequest = false;
      } else if (type === 'add') {
        goodsList.value = [...goodsList.value, ...(res.Result.records || [])];
      } else {
        goodsList.value = res.Result.records || [];
      }

      // getPageCount()
    } catch (error) {
      console.log(error);
      uni.hideLoading();
    } finally {
      uni.hideLoading();
    }

  }

  const handleSearch = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    getproductPage()
  }
  const handleReset = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    pageInfo.keyword = ''
    getproductPage()
  }

  // 切换
  const handlecurrentTab = async (index) => {
    currentTab.value = index
    pageInfo.status = undefined;
    if (index == 0) {
      getproductPage();
    }
  }
  // 切换等级
  const tabClick1 = (e) => {
    if (e.name == '全部') {
      pageInfo.levelName = undefined;
    } else {
      pageInfo.levelName = e.name;
    }

    pageInfo.limit = 20;
    pageInfo.page = 1;
    getproductPage();
  };
  // 切换状态
  const handlecurrentTabType = (index) => {
    if (index == 0) {
      pageInfo.status = undefined;
    } else if (index == 1) {
      pageInfo.status = 0;
    } else {
      pageInfo.status = 1;
    }
    pageInfo.limit = 20;
    pageInfo.page = 1;
    currentTabType.value = index
    getproductPage()

  }
  const handelDetail = () => {
    uni.navigateTo({
      url: '/pages/vip/vipDetails',
    })
  }
  // 积分调整
  const handleAdjust = () => {
    uni.navigateTo({
      url: '/pages/vip/pointsAdjustment',
    })
  }

  // 点击编辑
  const handleEdit = (item) => {
    showEditPopup.value = true;
    detailInfo.value=item
  }
  // 确定编辑
  const sureEditPopup = () => {
    showEditPopup.value = false;
  }
  // 关闭提编辑弹窗
  const closeEditPopup = () => {
    showEditPopup.value = false
  }
</script>

<style lang="scss" scoped>
  :deep(.u-tag) {
    padding: 0 5px !important;
  }

  :deep(.u-checkbox) {
    z-index: 999 !important;
  }

  .tabs-wrapper {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
    height: 44px;
    background: #fff;
    margin: 10px;

    :deep(.u-tabs) {
      width: 100% !important;

      .u-tabs__wrapper__nav__item {
        flex: 1 !important;
        white-space: nowrap;
      }

      .u-tabs__wrapper__nav__item__text {
        // white-space: nowrap;
      }
    }
  }

  .order-search {
    display: flex;
    background-color: #fff;
    margin: 0px 10px 0;
    padding: 12px 145px 12px 20px;
    box-sizing: border-box;

    .type-item {
      font-weight: 400;
      font-size: 14px;
      color: #666666;
      display: flex;
      align-items: center;
      background: #f6f6f6;
      padding: 7px 12px;
      box-sizing: border-box;
      border-radius: 10px;
      margin-right: 10px;
    }

    .activeType {
      background: rgba(15, 144, 253, 0.1);
      color: #0f90fd;
    }

    :deep(button) {
      width: 74px;
      height: 38px;
      margin-left: 11px;
      margin-right: 0;
      border-radius: 100px;
    }

    :deep(.uni-date) {
      margin-right: 10px;
    }

    :deep(.uni-date-x--border) {
      border-radius: 100px !important;
    }

    :deep(.uni-date-x) {
      border-radius: 100px !important;
    }
  }

  .vip-table {
    flex: 1;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .item-card {
      padding: 21px 10px 10px 22px;
      box-sizing: border-box;
      border-radius: 8px;
      margin: 10px;
      background: #FFFFFF;
      display: flex;

      .item-icon {
        width: 40px;
        height: 40px;
        margin-right: 19px;
      }

      /* 右侧区域：操作按钮 */
      .right-area {
        display: flex;
        flex-direction: column;
        flex: 1;
        justify-content: flex-end;

        .item-name {
          font-weight: 500;
          font-size: 16px;
          color: #333333;
          line-height: 22px;
        }

        .middle-area {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 23px;
          font-size: 14px;
          color: #666;
          flex-wrap: wrap;

          .info-item {
            font-weight: 400;
            font-size: 14px;
            color: #666666;
            white-space: nowrap;
          }

          .elliple {
            max-width: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            display: block;
            -webkit-box-orient: vertical;
          }

          .status {
            font-weight: 400;
            font-size: 14px;
            color: #666666;
            line-height: 20px;

            .status-dot {
              display: inline-block;
              width: 8px;
              height: 8px;
              border-radius: 50%;
              margin-right: 4px;

              &.enable {
                background-color: #52C41A;
              }

              &.disable {
                background-color: #F32F1D;
              }
            }
          }
        }

        .right-btn {
          display: flex;
          gap: 10px;
          flex-shrink: 0;
        }

        .operate-btn {
          display: flex;
          align-items: center;
          padding: 6px 12px;
          border-radius: 4px;
          box-sizing: border-box;
          font-weight: 400;
          font-size: 14px;
          color: #0F90FD;
          background: rgba(15, 144, 253, 0.1);
          border-radius: 100px;

          image {
            width: 16px;
            height: 16px;
            margin-right: 2px;
          }
        }
      }
    }



  }
</style>
